package blog.controller;


import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageInfo;
import com.service.ArticleService;
import com.service.CommentService;
import com.service.UserService;

import blog.entity.Article;
import blog.entity.Comment;
import blog.entity.User;



/**
 * 	User 控制层
 */
@Controller
@RequestMapping("/admin/user")
public class UserController {
	
	/**
	 *	 业务层对象，控制层只负责接受、传递参数，以及跳转。由业务层来调用持久层
	 */
	@Autowired
	private UserService  userService;
	@Autowired
	private ArticleService articleService;
	@Autowired
	private CommentService commentService;
	/**
	 * 	登录功能
	 * @param request 用它是为了减少方法参数
	 * @return	与视图解析器拼接的字符串，文件名
	 */
	@RequestMapping("/login")
	public String login(HttpServletRequest request) {
//		获取前端传递的数据
		String str=request.getParameter("userName");
		String password=request.getParameter("userPass");
//		根据用户名或邮箱查询用户
		User user =userService.getUserByNameOrEmail(str);
//		判断根据用户名或邮箱是否查询到了用户
		if(user!=null) {
//			查询到了，则判断前台传递的密码与查询到的用户是否匹配
			if(password.equals(user.getUserPass())) {
				request.getSession().setAttribute("session_user", user); 
				
				//查询最近的前5条文章
				List<Article> articleList= articleService.listRecentArticle(5);
				//查询最近的前5条评论
				List<Comment> commentList= commentService.listRecentComment(5);
				
				//将查询的数据传到首页
				request.setAttribute("articleList", articleList);
				request.setAttribute("commentList", commentList);
				//将用户信息放到Session中
				request.getSession().setAttribute("session_user", user);
				return "index"; 
			}
			else {
				//返回登录页面并提示密码错误
				request.setAttribute("msg", "密码错误");
				return "login";
			}
		}
//		程序能走到这个else，则说明根据用户名或邮箱没有找到用户
		else {
			//返回登录页面并提示账号错误
			request.setAttribute("msg", "账号错误");
			return "login";
		}
	}

	/**
	 * 	去添加用户页面
	 * @return
	 */
	@RequestMapping(value="/insert",method=RequestMethod.GET)
	public String gotoAddPage() {
		return "User/user-add";
	}
	
	/**
	 *	 执行添加用户
	 * @param user
	 * @param photo
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value="/insert",method=RequestMethod.POST)
	public String add(User user, MultipartFile photo) throws IOException {
		user.setUserRegisterTime(new Date());
		user.setUserPhoto(photo.getBytes());
		userService.addUser(user);
		
		return "forward:";
	}

	/**
	 * 	用户列表展示
	 * @param model
	 * @return
	 */
	@RequestMapping("")
	public String listUser(
			@RequestParam(required=false,defaultValue="1") Integer pageIndex,
			@RequestParam(required=false,defaultValue="5")  Integer pageSize,
			Map<String,Object> model) {
		PageInfo<User> userList=userService.ListUser(pageIndex,pageSize);
		model.put("pageInfo", userList);
		model.put("pageUrlPrefix", "admin/user?pageIndex"); 
		return "User/user-list";
	}
	
	@RequestMapping("/photo/{userId}")
	public void getPhoto(@PathVariable("userId") Integer userId, HttpServletResponse response ) throws IOException {
		User user=userService.getUserById(userId);
		
		response.setContentType("image/jpg");
		ServletOutputStream outStream =response.getOutputStream();
		outStream.write(user.getUserPhoto());
		
		outStream.flush();
	}
	
	/**
	 * 	回首页
	 * @return
	 */
	@RequestMapping("/index")
	private String goIndex(HttpServletRequest request) {
		User user = (User)request.getSession().getAttribute("session_user");
		return "forward:/admin/user/login?userName="+user.getUserName()+"&userPass="+user.getUserPass();
	}
}
